package com.easy.web.utils;


import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * Created by 郏高阳 on 2016/7/6.
 */
public class SystemUtils {

    /**
     * 获取用户IP地址
     *
     * @param request
     * @return
     */
    public static String getRemortIP(HttpServletRequest request) {
        if (request.getHeader("x-forwarded-for") == null) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    /**
     * 字符串中文编码
     * @param cnStr
     * @return
     */
    public static String getUrlEncode(String cnStr){
        try {
            return new String(java.net.URLEncoder.encode(cnStr, "UTF-8").getBytes(), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return cnStr;
    };

    /**
     * 字符串进行编码
     * @param str 转换的内容
     * @param charset   utf-8
     * @return
     */
    public static String encodeUrlString(String str, String charset) {
        String strret = null;
        if (str == null)
            return str;
        try {
            strret = java.net.URLEncoder.encode(str, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return strret;
    }

    /**
     * 排除部分JSON中的key
     * @param stringList
     * @return
     */
    public static JsonConfig getExcludekeycfg(List<String> stringList){
        JsonConfig cfg = new JsonConfig();
        cfg.setJsonPropertyFilter((source, name, value) -> stringList.indexOf(name) > -1);
        return cfg;
    }

    /**
     * 根据IP地址查询归属地
     * @param ipStr
     * @return
     */
    public static String getIPLocationAddress(String ipStr) {
        String httpUrl = "http://apis.baidu.com/apistore/iplookup/iplookup_paid?";
        String httpArg = "ip=" + ipStr;
        String result = getHttp(httpUrl + httpArg);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject jsonBody = jsonObject.optJSONObject("retData");
        if(jsonBody != null){
            String country = jsonBody.optString("country");
            String province = jsonBody.optString("province");
            String city = jsonBody.optString("city");
            String district = jsonBody.optString("district");
            return country + province + city + district+".";
        }
        return "未知";
    }

    /**
     * get请求
     * @param httpUrl  URL地址
     * @return
     */
    public static String getHttp(String httpUrl) {
        StringBuffer sbf = new StringBuffer();
        BufferedReader reader = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("apikey",  "b2b4bcef2a35e750af1521144d25cee1");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
